<!-- pages/post/post.vue -->
<template>
	<view class="wrapper">
		<form @submit="handleSubmit">
			
			<view class="form-item">
				<text>动态内容:</text>
				<!-- 正确写法：所有属性都写在 textarea 标签上 -->
				<textarea 
					name="content" 
					v-model="content" 
					placeholder="分享校园新鲜事..." 
				/>
			</view>
			
			<!-- (下节课再做图片上传) -->

			<!-- 2. 提交按钮 -->
			<button type="primary" form-type="submit" :loading="isLoading">
				{{isLoading ? '发布中...' : '立即发布'}}
			</button>
		</form>
	</view>
</template>

<script setup>
import { ref } from 'vue';

// 1. 初始化数据库"遥控器"
const db = uniCloud.database();

const isLoading = ref(false);
// 定义响应式变量（必须有）
const content = ref('');

// 2. 表单提交事件
const handleSubmit = async (e) => {
	const postContent = content.value.trim();
	
	// 简单验证
	if (!postContent) {
		uni.showToast({ title: '内容不能为空', icon: 'error' });
		return;
	}
	
	isLoading.value = true;
	
	try {
		// 3. 【核心】向 'campus-posts' 表"添加" (add) 一条数据
		const res = await db.collection('campus-posts').add({
			content: postContent,
			like_count: 0,
			publish_time: Date.now()
		});
		
		console.log('发布成功', res);
		uni.showToast({ title: '发布成功！', icon: 'success' });
		
		// 清空输入框（核心）
		content.value = '';
		
	} catch (err) {
		console.error('发布失败', err);
		uni.showToast({ title: '发布失败，请重试', icon: 'error' });
	} finally {
		isLoading.value = false;
	}
};
</script>

<style>
.wrapper {
	padding: 15px;
}
.form-item {
	margin-bottom: 15px;
}
.form-item text {
	font-weight: bold;
	display: block;
	margin-bottom: 5px;
}
.form-item textarea {
	width: 100%;
	height: 120px;
	padding: 10px;
	border: 1px solid #eee;
	border-radius: 5px;
	background-color: #fff;
	box-sizing: border-box;
}
</style>